package com.ct.onlinemusic.controller;

import com.ct.onlinemusic.enums.ResultCode;
import com.ct.onlinemusic.model.UserInfo;
import com.ct.onlinemusic.service.UserSeivice;
import com.ct.onlinemusic.tools.Constant;
import com.ct.onlinemusic.tools.ResponseMessage;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@Slf4j
@RestController
@RequestMapping("/user")
public class UserContrller {
    @Autowired
    private UserSeivice userSeivice;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 登录
     * @param username  用户名
     * @param password  密码
     * @param session   服务器记录登录信息
     * @return          登录信息
     */
    @RequestMapping("/login")
    public ResponseMessage<UserInfo> login (String username, String password, HttpSession session) {
        log.info("登录:{}", username);
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return new ResponseMessage<>(ResultCode.UNLOGIN.getCode(), "用户名或密码不能为空", new UserInfo(username, password));
        }
        UserInfo userInfo = userSeivice.checkPassword(username, password);
        if (userInfo == null) return null;
        else {
            boolean matches = bCryptPasswordEncoder.matches(password, userInfo.getPassword());
            System.out.println(matches);
            if (matches) {
                session.setAttribute(Constant.USERINFO_SESSION_KEY, userInfo);
                return new ResponseMessage<>(ResultCode.SUCCESS.getCode(), "登录成功", userInfo);
            } else {
                return new ResponseMessage<>(ResultCode.UNLOGIN.getCode(), "用户名或密码错误", userInfo);
            }
        }
    }
}
